import os
import random
import time
from cnocr import CnOcr
from fastapi import FastAPI, Request,UploadFile
import uvicorn, json, datetime




app = FastAPI()


def predict_file(filepath):
    try:
        out = OCR_gene.ocr(filepath)
        answer = {
            "file_name": filepath,
            "message": "success",
            "code": 200,
            "result": str(out)
        }
        return answer
    except Exception as e:
        error_info = {
            "exception_type": type(e).__name__,
            "description": e.args[0]
        }
        json_error_info = json.dumps(error_info)
        answer = {
            "file_name": "",
            "message": json_error_info,
            "code": 500,
            "result": ""
        }
        return answer


@app.post("/tontronocr/server/img")
async def ocr(file: UploadFile):
    try:
        # 保存文件的文件名格式为年-月-日-时-分-秒-三位随机数.wav
        now_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
        # 验证码文件存储路径
        file_save_path = "img_files"
        if not os.path.exists(file_save_path):
            os.makedirs(file_save_path)
        YMD = time.strftime('%Y-%m-%d', time.localtime())
        if not os.path.exists(os.path.join(file_save_path, YMD)):
            os.makedirs(os.path.join(file_save_path, YMD))
        filepath = os.path.join(file_save_path, YMD) + separator + now_time + "__" + random.randint(100,
                                                                                                    999).__str__() + ".jpg "
        contents = await file.read()
        with open(filepath, "wb") as f:
            f.write(contents)
        return predict_file(filepath)
    except Exception as e:
        error_info = {
            "exception_type": type(e).__name__,
            "description": e.args[0]
        }
        json_error_info = json.dumps(error_info)
        answer = {
            "file_name": "",
            "message": json_error_info,
            "code": 500,
            "result": ""
        }
        return answer

if __name__ == '__main__':
    OCR_gene = CnOcr()  # 所有参数都使用默认值
    separator = os.sep
    uvicorn.run(app, host='0.0.0.0', port=7000, workers=1)
